package it.orma.iridehr.views;

import it.orma.iridehr.controllers.ricerca.AttitudiniForm;
import it.orma.iridehr.entities.Attitudine;
import it.orma.iridehr.entities.DatiGenerali;
import it.orma.iridehr.entities.DomandaAttitudinale;
import it.orma.iridehr.entities.EsperienzaLavorativa;
import it.orma.iridehr.entities.RispostaAttitudinale;
import it.orma.iridehr.entities.SchedaCandidato;
import it.orma.iridehr.entities.StudiCompiuti;
import it.orma.iridehr.entities.TitoloDiStudio;
import it.orma.iridehr.repository.RicercaRepository;
import it.orma.iridehr.services.helper.DocumentoAlfresco;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

public class CVPreviewAnalisiView extends AbstractPdfView {

	
	String url;
	
	@Override
	protected void buildPdfDocument(Map<String, Object> model, Document doc,
			PdfWriter writer, HttpServletRequest request, HttpServletResponse arg4)
			throws Exception {
		doc.open();
		doc.setPageSize(PageSize.A4);
		DatiGenerali dg = (DatiGenerali) model.get("dg");
		List<DomandaAttitudinale> domande = (List<DomandaAttitudinale>)model.get("domande");
		List<Attitudine> attitudini = ((AttitudiniForm)model.get("attitudiniForm")).getAttitudini();
		InputStream logois = new FileInputStream(new File( (String) model.get("logo")));
		
		Paragraph paragraph = new Paragraph();		
		byte[] logob = new byte[logois.available()];
		logois.read(logob);
    	Image image = Image.getInstance(logob);
        image.setAlignment(Image.ALIGN_LEFT);
        paragraph.add(new Chunk("Test"));
        logois.close();

		BaseFont bf = createFont();
		PdfPTable table = new PdfPTable(new float[]{30f,2f,2f,66f});
		Phrase mainCV = new Phrase();
		mainCV.add(new Chunk(dg.getNome().substring(0,1).toUpperCase(),new Font(bf,13,Font.BOLD)));
		mainCV.add(new Chunk(dg.getNome().substring(1).toUpperCase(),new Font(bf,10,Font.BOLD)));
		mainCV.add(new Chunk(" "+dg.getCognome().substring(0,1).toUpperCase(),new Font(bf,13,Font.BOLD)));
		mainCV.add(new Chunk(dg.getCognome().substring(1).toUpperCase(),new Font(bf,10,Font.BOLD)));
		mainCV.add(new Chunk("\nC",new Font(bf,13,Font.BOLD)));
		mainCV.add(new Chunk("URRICULUM ",new Font(bf,10,Font.BOLD)));
		mainCV.add(new Chunk("V",new Font(bf,13,Font.BOLD)));
		mainCV.add(new Chunk("ITAE",new Font(bf,10,Font.BOLD)));
				
		PdfPCell leftCell = new PdfPCell(mainCV);
		leftCell.setBorder(0);
		
		PdfPCell centerCell1 = new PdfPCell(new Phrase(""));
		centerCell1.setBorder(Rectangle.RIGHT);
		PdfPCell centerCell2 = new PdfPCell(new Phrase(""));
		centerCell2.setBorder(0);
		
		PdfPCell rightCell ;
		
		if (dg.getFoto()!=null)
			rightCell = new PdfPCell(Image.getInstance(dg.getFoto()));
		else 
			rightCell = new PdfPCell(new Phrase(""));
		
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_CENTER);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase(" ",new Font(bf,13,Font.BOLD)));
		leftCell.setBorder(0);
		rightCell = new PdfPCell(new Phrase(" ",new Font(bf,13,Font.BOLD)));
		rightCell.setBorder(0);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		Phrase personalInfo = new Phrase();
		personalInfo.add(new Chunk("I",new Font(bf,11,Font.BOLD)));
		personalInfo.add(new Chunk("NFORMAZIONI",new Font(bf,9,Font.BOLD)));
		personalInfo.add(new Chunk(" P".toUpperCase(),new Font(bf,11,Font.BOLD)));
		personalInfo.add(new Chunk("ERSONALI",new Font(bf,9,Font.BOLD)));		
		leftCell = new PdfPCell(personalInfo);
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(" ",new Font(bf,13,Font.BOLD)));
		rightCell.setBorder(0);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Cognome e Nome",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getCognome()+" "+dg.getNome(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Luogo e data di nascita",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getComuneDiNascita()+","+new SimpleDateFormat("dd/MM/yyyy").format(dg.getDataDiNascita()),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Residenza",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getIndirizzoResidenza()+","+dg.getCapResidenza()+" "+dg.getComuneResidenza(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Nazionalità",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getNazionalita(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Sesso",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getSesso(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Stato civile",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getStatoCivile(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Telefono fisso",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getTelefonoCasa(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);
		
		leftCell = new PdfPCell(new Phrase("Telefono mobile",new Font(bf,9,Font.NORMAL)));
		leftCell.setBorder(0);
		leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		rightCell = new PdfPCell(new Phrase(dg.getTelefonoCell1(),new Font(bf,9,Font.NORMAL)));
		rightCell.setBorder(0);
		rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
		table.addCell(leftCell);
		table.addCell(centerCell1);
		table.addCell(centerCell2);
		table.addCell(rightCell);		
		
		doc.add(table);
		
		PdfPTable tableAtt = new PdfPTable(new float[]{6f,19f,19f,19f,19f,8f,8f});
		tableAtt.setWidthPercentage(90f);
		PdfPCell cellH = new PdfPCell(new Phrase(" ",new Font(bf,30,Font.BOLD)));
		cellH.setBorder(0);
		cellH.setColspan(7);
		cellH.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cellH);
		
		PdfPCell cell1 = new PdfPCell(new Phrase(""));
		cell1.setBorder(0);
		cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell1);
		PdfPCell cell2 = new PdfPCell(new Phrase("Voce A",new Font(bf,10,Font.BOLD)));
		cell2.setBorder(0);
		cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell2);
		PdfPCell cell3 = new PdfPCell(new Phrase("Voce B",new Font(bf,10,Font.BOLD)));
		cell3.setBorder(0);
		cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell3);
		PdfPCell cell4 = new PdfPCell(new Phrase("Voce C",new Font(bf,10,Font.BOLD)));
		cell4.setBorder(0);
		cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell4);
		PdfPCell cell5 = new PdfPCell(new Phrase("Voce D",new Font(bf,10,Font.BOLD)));
		cell5.setBorder(0);
		cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell5);
		PdfPCell cell6 = new PdfPCell(new Phrase("Meglio",new Font(bf,10,Font.BOLD)));
		cell6.setBorder(0);
		cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell6);
		PdfPCell cell7 = new PdfPCell(new Phrase("Peggio",new Font(bf,10,Font.BOLD)));
		cell7.setBorder(0);
		cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
		tableAtt.addCell(cell7);
		
		Iterator<DomandaAttitudinale> it = domande.iterator();
		Iterator<Attitudine> attIt = attitudini.iterator();
		int i=1;
		while(it.hasNext()){
			
			DomandaAttitudinale recordDomande = it.next();
			Attitudine recordAtt = attIt.next();
			PdfPCell cellIndex = new PdfPCell(new Phrase(""+i,new Font(bf,9,Font.BOLD)));
			cellIndex.setBorder(0);
			cellIndex.setHorizontalAlignment(Element.ALIGN_CENTER);
			tableAtt.addCell(cellIndex);
			Iterator<RispostaAttitudinale> inner = recordDomande.getRisposte().iterator();
			while(inner.hasNext()){
				RispostaAttitudinale risposta = inner.next();
				PdfPCell cellRisposta = new PdfPCell(new Phrase(risposta.getTesto(),new Font(bf,9,Font.NORMAL)));
				cellRisposta.setBorder(0);
				cellRisposta.setHorizontalAlignment(Element.ALIGN_CENTER);
				tableAtt.addCell(cellRisposta);
			}
			Long idRispostaMeglio = recordAtt.getIdRispostaMeglio();
			String rispostaMeglio = "-";
			if(idRispostaMeglio.longValue()==1)
				rispostaMeglio = "A";
			else if(idRispostaMeglio.longValue()==2)
				rispostaMeglio = "B";
			else if(idRispostaMeglio.longValue()==3)
				rispostaMeglio = "C";
			else if(idRispostaMeglio.longValue()==4)
				rispostaMeglio = "D";
			PdfPCell cellMeglio = new PdfPCell(new Phrase(rispostaMeglio,new Font(bf,9,Font.NORMAL)));
			cellMeglio.setBorder(0);
			cellMeglio.setHorizontalAlignment(Element.ALIGN_CENTER);
			tableAtt.addCell(cellMeglio);
			Long idRispostaPeggio = recordAtt.getIdRispostaPeggio();
			String rispostaPeggio = "-";
			if(idRispostaPeggio.longValue()==1)
				rispostaPeggio = "A";
			else if(idRispostaPeggio.longValue()==2)
				rispostaPeggio = "B";
			else if(idRispostaPeggio.longValue()==3)
				rispostaPeggio = "C";
			else if(idRispostaPeggio.longValue()==4)
				rispostaPeggio = "D";
			PdfPCell cellPeggio = new PdfPCell(new Phrase(rispostaPeggio,new Font(bf,9,Font.NORMAL)));
			cellPeggio.setBorder(0);
			cellPeggio.setHorizontalAlignment(Element.ALIGN_CENTER);
			tableAtt.addCell(cellPeggio);
			i++;
		}
		
		doc.add(tableAtt);
		/*
		DocumentoAlfresco docAlf = (DocumentoAlfresco)model.get("docAlfresco");
		
		byte[] array = new byte[docAlf.getStream().available()];
		docAlf.getStream().read(array);
		PdfImportedPage page;
		PdfReader reader = new PdfReader(array);
        int numberOfPages = reader.getNumberOfPages();
       
        doc.open();
        for(int i = 0; i < numberOfPages; ){
            ++i;
            doc.open();
            PdfContentByte cb = writer.getDirectContent();

	        page = writer.getImportedPage(reader, i); 
	
	        // Copy first page of existing PDF into output PDF
	        doc.newPage();
	        cb.addTemplate(page, 0, 0);            
        }
        doc.close();
        writer.close();
        */
		
	}
	
	private BaseFont createFont() throws DocumentException, IOException{
		BaseFont bf= BaseFont.createFont("/fonts/arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		return bf;
	}

	@Override
	protected void buildPdfMetadata(Map<String, Object> model,
			Document document, HttpServletRequest request) {
		// TODO Auto-generated method stub
		super.buildPdfMetadata(model, document, request);
		
		InputStream logois;
		try {
			logois = new FileInputStream(new File( (String) model.get("logo")));
			
			Paragraph paragraph = new Paragraph();		
			
			byte[] logob = new byte[logois.available()];
			logois.read(logob);
	    	Image image = Image.getInstance(logob);
	        image.setAlignment(Image.ALIGN_LEFT);
	        paragraph.add(new Chunk(image, 0.0F, 0F));
	        logois.close();
	        
			HeaderFooter header = new HeaderFooter(paragraph,false);
			
			header.setBorder(0);
			document.setMargins(20, 20, 75, 40);
	            
	        document.setHeader(header);
	        
	        Paragraph paragraph2 = new Paragraph();		
	        paragraph2.add(new Chunk("                  Orma S.r.l. Via Enrico Fermi, 93 22030 Orsenigo(CO) - Tel.031.619.891 - Fax 031.33.50.058\n"+
	        		                 "                  www.orma.ws    -    email:     info@orma.ws    -   Cod.   Fisc.    e    Partita  IVA  02342930134",new Font(Font.HELVETICA,11,Font.NORMAL)));
	        paragraph2.setAlignment(Element.ALIGN_MIDDLE|Element.ALIGN_JUSTIFIED);
	        HeaderFooter footer = new HeaderFooter(paragraph2,false);
			document.setFooter(footer);
			footer.setBorder(0);
	        
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (BadElementException e) {
			e.printStackTrace();
		}
		
	}
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	

}
